package io.gitee.sfch.chunmi.controller.system;

import io.gitee.sfch.chunmi.entity.Response;
import io.gitee.sfch.chunmi.controller.system.form.SystemLoginForm;
import io.gitee.sfch.chunmi.dao.system.entity.SystemUser;
import io.gitee.sfch.chunmi.service.system.LoginService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RestController
@RequestMapping("/system")
public class SystemLoginController {

    @Resource
    private LoginService loginService;

    /**
     * 账户登录
     */
    @PostMapping("/login")
    public Response<String> login(@RequestBody SystemLoginForm form, HttpServletRequest servletRequest) {
        loginService.login(form, servletRequest);
        return Response.successEmpty("");
    }

    /**
     * 确认登录状态，每次刷新页面时调用。
     * <p>
     * 使用Session-Cookie登录的情况下，前端在刷新后无法判定当前是否登录（因为Cookie无法读取），所以在进入页面时，需求请求该接口以获取服务器的
     * 用户登录状态
     */
    @GetMapping("/login/status")
    public String alreadyLogin(HttpServletRequest servletRequest) {
        boolean res = loginService.alreadyLogin(servletRequest);
        return Boolean.toString(res);
    }

    /**
     * 登出
     */
    @PutMapping("/logout")
    public Response<String> logout(HttpServletRequest servletRequest) {
        loginService.logout(servletRequest);
        return Response.successEmpty("");
    }

    /**
     * 获取当前的用户信息
     */
    @GetMapping("/info")
    public Response<SystemUser> info(HttpServletRequest servletRequest) {
        SystemUser systemUser = loginService.getSessionUser(servletRequest);
        return Response.success(systemUser);
    }
}
